package com.example.managemyself.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import androidx.core.app.ActivityCompat;

/**
 * 位置管理工具类
 * 用于获取用户当前位置
 */
public class LocationHelper {
    
    private static final String TAG = "LocationHelper";
    private static final int LOCATION_TIMEOUT = 10000; // 10秒超时
    
    private LocationManager locationManager;
    private Context context;
    
    public LocationHelper(Context context) {
        this.context = context;
        this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }
    
    /**
     * 获取当前位置
     */
    public void getCurrentLocation(LocationCallback callback) {
        if (!checkLocationPermission()) {
            callback.onError("没有位置权限");
            return;
        }
        
        if (!isLocationEnabled()) {
            callback.onError("位置服务未开启");
            return;
        }
        
        try {
            // 首先尝试获取最后已知位置
            Location lastKnownLocation = getLastKnownLocation();
            if (lastKnownLocation != null && isRecentLocation(lastKnownLocation)) {
                callback.onLocationReceived(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                return;
            }
            
            // 创建位置监听器
            LocationListener locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        locationManager.removeUpdates(this);
                        callback.onLocationReceived(location.getLatitude(), location.getLongitude());
                    }
                }
                
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {}
                
                @Override
                public void onProviderEnabled(String provider) {}
                
                @Override
                public void onProviderDisabled(String provider) {
                    callback.onError("位置提供者被禁用: " + provider);
                }
            };
            
            // 请求位置更新
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 
                    0, 
                    0, 
                    locationListener
                );
            } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 
                    0, 
                    0, 
                    locationListener
                );
            } else {
                callback.onError("没有可用的位置提供者");
            }
            
            // 设置超时
            new android.os.Handler().postDelayed(() -> {
                locationManager.removeUpdates(locationListener);
                callback.onError("获取位置超时");
            }, LOCATION_TIMEOUT);
            
        } catch (SecurityException e) {
            Log.e(TAG, "位置权限异常", e);
            callback.onError("位置权限异常");
        } catch (Exception e) {
            Log.e(TAG, "获取位置异常", e);
            callback.onError("获取位置异常: " + e.getMessage());
        }
    }
    
    /**
     * 检查位置权限
     */
    private boolean checkLocationPermission() {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
               ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }
    
    /**
     * 检查位置服务是否启用
     */
    private boolean isLocationEnabled() {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
               locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
    
    /**
     * 获取最后已知位置
     */
    private Location getLastKnownLocation() {
        try {
            Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            
            if (gpsLocation != null && networkLocation != null) {
                return gpsLocation.getTime() > networkLocation.getTime() ? gpsLocation : networkLocation;
            } else if (gpsLocation != null) {
                return gpsLocation;
            } else {
                return networkLocation;
            }
        } catch (SecurityException e) {
            Log.e(TAG, "获取最后已知位置失败", e);
            return null;
        }
    }
    
    /**
     * 检查位置是否是最近的（5分钟内）
     */
    private boolean isRecentLocation(Location location) {
        long currentTime = System.currentTimeMillis();
        long locationTime = location.getTime();
        return (currentTime - locationTime) < 5 * 60 * 1000; // 5分钟
    }
    
    /**
     * 位置回调接口
     */
    public interface LocationCallback {
        void onLocationReceived(double latitude, double longitude);
        void onError(String error);
    }
} 